package com.smalls.newvideotwo.mvp.model;

import android.os.Handler;

import com.smalls.newvideotwo.Constants;
import com.smalls.newvideotwo.NewDTVApp;
import com.smalls.newvideotwo.mvp.base.BaseBeanResult;
import com.smalls.newvideotwo.mvp.beanResult.GetHotMovieResult;
import com.smalls.newvideotwo.mvp.http.Result;
import com.smalls.newvideotwo.mvp.model.modelInterface.IGetHotMovie;
import com.smalls.newvideotwo.util.LogUtil;
import com.smalls.newvideotwo.util.UIHelper;
import com.smalls.newvideotwo.utils.Constant;

import java.io.IOException;
import java.net.SocketTimeoutException;

import okhttp3.Call;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by cindy on 2018/3/21.
 */

public class GetAllMovieModel implements IGetHotMovie {
    private static String TAG = Constant.baddcoolio2tag? Constant.TAGPREFIXSTR + "GetAllMovieModel":"GetAllMovieModel";
    Handler handler = new Handler();
    private Call call;
    private int serversLoadTimes = 0;
    public void Abort() {
        handler.removeCallbacksAndMessages(null);
        if(call!=null&&!call.isCanceled()) {
            call.cancel();
        }
    }
    @Override
    public void getHotMovie(final BaseBeanResult baseBeanResult,int start,int end) {
        LogUtil.d(this.TAG, "getHotMovie");
        final Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("Range",start+"-"+end)
                .addHeader("Authorization","Bearer "+ NewDTVApp.getApp().getToken())
                .url(Constants.API_DETAIL())
                .get()
                .build();

        final OkHttpClient client = new OkHttpClient.Builder()
                //.addInterceptor(NewDTVApp.getApp().loggingInterceptor)
                .build();
        try{
        call = client.newCall(request);
        call.enqueue(new okhttp3.Callback() {
                    @Override
                    public void onFailure(Call call, final IOException e) {
                        if(e.getCause().equals(SocketTimeoutException.class) && serversLoadTimes<3)//如果超时并未超过指定次数，则重新连接
                        {
                            serversLoadTimes++;
                            client.newCall(call.request()).enqueue(this);
                        }else {
                            e.printStackTrace();
                            baseBeanResult.onError(e);
                            //UIHelper.toastServerConnectErr();
                        }

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        final String resultStr = response.body().string();
                    if(response.code()!=200) {
                        baseBeanResult.onError(new Exception());
                        return;
                    }
                        handler.post(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    String addData = "{data:"+resultStr+"}";
                                    GetHotMovieResult result = Result.getResult(addData, GetHotMovieResult.class);
                                    if (result!=null) {
                                        baseBeanResult.onNext(result);
                                        return;
                                    }
                                    /// toastServerResponseErr(result.errorMessage);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    baseBeanResult.onError(e);
                                    //UIHelper.toastServerResponseErr("something wrong with data.");
                                }
                            }
                        });

                    }
                });
        } catch (Exception e) {
            e.printStackTrace();
            baseBeanResult.onError(e);
            //UIHelper.toastServerResponseErr("something wrong with data.");
        }
    }
}
